package com.zhu.servlet;

import com.zhu.dao.ClassDao;
import com.zhu.dao.HobbyDao;
import com.zhu.dao.StudentDao;
import com.zhu.pojo.Classes;
import com.zhu.pojo.Hobby;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/addStudent.do")
public class AddStuServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Classes> classesList=null;
        List<Hobby> hobbyList=null;
        try {
            classesList = new ClassDao().getClasses();
            hobbyList = new HobbyDao().getHobby();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        req.setAttribute("classesList",classesList);
        req.setAttribute("hobbyList",hobbyList);
        req.getRequestDispatcher("/WEB-INF/jsp/addStudent.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int hid=0;
        String[] hobbies = req.getParameterValues("hobby");
        for (String hobby : hobbies) {
            hid += Integer.parseInt(hobby);
        }

        String sname = req.getParameter("sname");
        int cid = Integer.parseInt(req.getParameter("cid"));
        new StudentDao().insertStudent(sname,cid,hid);
        resp.sendRedirect("index.do");
    }
}
